import { forwardRef, useImperativeHandle } from 'react';
import { FlatList, View, LayoutRectangle } from 'react-native';
import Empty from './empty';
import NoMore from './noMore';
import Resize from '../Resize';
import Skeleton from '../Skeleton';
import FooterLoading from './loading';
import { useSplitPage } from './hooks';
import type { ScrollLoadMoreProps, InstanceType } from './types';
import styles from './styles';

const createLoadMore = <Record=any>() => forwardRef<
  InstanceType<Record>, 
  ScrollLoadMoreProps<Record>
>((props, ref) => {
  const {
    request,
    emptyProps,
    renderItem,
    pageSize
  } = props;

  const {
    page,
    empty,
    datas,
    noMore,
    refresh,
    loading,
    getDatas,
    refreshing,
    toNextPage
  } = useSplitPage<Record>(request, pageSize);

  const renderDivide = () => {
    return <View style={props.divideLineStyle} />;
  }

  // 渲染空
  const renderEmpty = (layout: LayoutRectangle) => {
    if (loading) {
      return <Skeleton {...layout} />;
    } else {
      return <Empty {...layout} {...emptyProps} />;
    }
  }

  const renderFooterLoading = () => {
    let element = null;
    const init = page === 1 && loading;
    if (init || empty) return element;

    if (noMore) {
      element = <NoMore />;
    } else if (loading && page > 1) {
      element = <FooterLoading />;
    }
    return (
      <View style={styles.footer}>
        {element}
      </View>
    );
  }

  useImperativeHandle(ref, () => {
    return { refresh, getDatas };
  });

  return (
    <Resize style={styles.wrapper}>
      {layout => (
        <FlatList<Record>
          data={datas}
          onRefresh={refresh}
          overScrollMode="never"
          refreshing={refreshing}
          renderItem={renderItem}
          onEndReached={toNextPage}
          onEndReachedThreshold={50}
          showsVerticalScrollIndicator={false}
          ItemSeparatorComponent={renderDivide}
          ListEmptyComponent={renderEmpty(layout)}
          ListFooterComponent={renderFooterLoading()}
        />
      )}
    </Resize>
  );
});

export default createLoadMore